#!/bin/bash

# 颜色定义
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
blue='\033[0;34m'
plain='\033[0m'

# 基础配置
MENU_DIR="$yz/plugins/XRK/resources/plugins"
CATEGORIES=(
    "推荐插件:recommended_plugins.json"
    "文娱插件:entertainment_plugins.json"
    "IP类插件:ip_plugins.json"
    "游戏插件:game_plugins.json"
    "JS插件:js.json"
)
YZ_DIR="$yz"

source /xrk/shell_modules/github.sh

# 清屏函数
clear_lines() {
    local lines=$1
    for ((i = 0; i < lines; i++)); do
        printf "\e[1A\e[K"
    done
}

# 检查依赖
check_dependencies() {
    clear
    local deps=("jq" "dialog" "git" "pnpm" "curl")
    local missing_deps=()

    for dep in "${deps[@]}"; do
        if ! command -v "$dep" &>/dev/null; then
            missing_deps+=("$dep")
        fi
    done

    if [ ${#missing_deps[@]} -ne 0 ]; then
        echo -e "${caidan2}正在安装缺失的依赖: ${missing_deps[*]}${bg}"
        if grep -Eqi "Ubuntu" /etc/issue && grep -Eq "Ubuntu" /etc/*-release; then
            apt update && apt install -y "${missing_deps[@]}"
        elif [ -f /etc/arch-release ]; then
            pacman -Sy --noconfirm "${missing_deps[@]}"
        elif [ -f /etc/redhat-release ]; then
            yum install -y "${missing_deps[@]}"
        else
            echo -e "${red}无法确定包管理器，请手动安装: ${missing_deps[*]}${bg}"
            return 1
        fi
    fi
}

# 安装Python环境
install_python_env() {
    echo -e "${caidan2}正在检查 Python 环境...${bg}"
    
    # 检测系统架构
    local arch=$(uname -m)
    echo -e "${caidan2}检测到系统架构: $arch${bg}"
    
    local PYTHON_CMD=""
    if command -v python3 &>/dev/null; then
        PYTHON_CMD="python3"
    elif command -v python &>/dev/null; then
        PYTHON_CMD="python"
    fi

    if [ -z "$PYTHON_CMD" ]; then
        echo -e "${caidan2}未检测到 Python，开始安装...${bg}"
        
        # Debian/Ubuntu系
        if command -v apt &>/dev/null; then
            echo -e "${caidan2}检测到Debian/Ubuntu系统${bg}"
            apt update
            # 使用--no-install-recommends减少安装不必要的依赖
            apt install -y --no-install-recommends python3 python3-pip python3-venv python3-dev
            
            # ARM架构可能需要额外的依赖
            if [[ "$arch" == "arm"* || "$arch" == "aarch64" ]]; then
                echo -e "${caidan2}ARM架构，安装额外依赖...${bg}"
                apt install -y --no-install-recommends build-essential libffi-dev
            fi
            
            PYTHON_CMD="python3"
            
        # Arch系
        elif command -v pacman &>/dev/null; then
            echo -e "${caidan2}检测到Arch系统${bg}"
            pacman -Sy --needed --noconfirm python python-pip
            
            if [[ "$arch" == "arm"* || "$arch" == "aarch64" ]]; then
                pacman -Sy --needed --noconfirm base-devel
            fi
            
            PYTHON_CMD="python"
            
        # Red Hat/CentOS系
        elif command -v yum &>/dev/null; then
            echo -e "${caidan2}检测到Red Hat/CentOS系统${bg}"
            yum install -y python3 python3-pip python3-devel
            
            if [[ "$arch" == "arm"* || "$arch" == "aarch64" ]]; then
                yum install -y gcc libffi-devel
            fi
            
            PYTHON_CMD="python3"
            
        # macOS
        elif command -v brew &>/dev/null; then
            echo -e "${caidan2}检测到macOS系统${bg}"
            brew install python
            PYTHON_CMD="python3"
            
        else
            echo -e "${red}无法确定包管理器，请手动安装 Python${bg}"
            return 1
        fi
    fi
    
    # 确保pip已安装并可用
    echo -e "${caidan2}检查pip是否可用...${bg}"
    local PIP_CMD=""
    
    if command -v pip3 &>/dev/null; then
        PIP_CMD="pip3"
    elif command -v pip &>/dev/null; then
        PIP_CMD="pip"
    elif [ -n "$PYTHON_CMD" ]; then
        echo -e "${caidan2}尝试通过ensurepip安装pip...${bg}"
        $PYTHON_CMD -m ensurepip --upgrade --default-pip || {
            echo -e "${caidan2}尝试通过get-pip.py安装pip...${bg}"
            curl -s https://bootstrap.pypa.io/get-pip.py -o get-pip.py
            $PYTHON_CMD get-pip.py --force-reinstall
            rm -f get-pip.py
        }
        
        # 再次检查pip是否可用
        if command -v pip3 &>/dev/null; then
            PIP_CMD="pip3"
        elif command -v pip &>/dev/null; then
            PIP_CMD="pip"
        else
            echo -e "${red}pip安装失败，请手动安装${bg}"
            return 1
        fi
    fi
    
    # 配置pip镜像源
    if [ ! -f ~/.pip/pip.conf ]; then
        echo -e "${caidan2}配置 pip 镜像源...${bg}"
        mkdir -p ~/.pip
        cat > ~/.pip/pip.conf << EOF
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
trusted-host = mirrors.aliyun.com
EOF
    fi

    # 安装Poetry
    if ! command -v poetry &>/dev/null; then
        echo -e "${caidan2}正在安装 Poetry...${bg}"
        
        # 使用curl方式安装Poetry
        curl -sSL https://install.python-poetry.org | $PYTHON_CMD -
        
        # 配置环境变量
        if ! grep -q "POETRY_HOME" ~/.profile; then
            echo -e "${caidan2}配置 Poetry 环境变量...${bg}"
            cat >> ~/.profile << EOF
# Python Poetry 环境变量
export PATH="\$HOME/.local/bin:\$PATH"
export POETRY_HOME="\$HOME/.poetry"
EOF
        fi

        # 立即应用环境变量
        export PATH="$HOME/.local/bin:$PATH"
        export POETRY_HOME="$HOME/.poetry"
        # 如果~/.profile文件不存在，创建一个
        if [[ ":$PATH:" != *":$HOME/.poetry/bin:"* ]]; then
            export PATH="$HOME/.poetry/bin:$PATH"
        fi
        
        # 配置Poetry
        echo -e "${caidan2}配置 Poetry...${bg}"
        if command -v poetry &>/dev/null; then
            poetry config repositories.aliyun https://mirrors.aliyun.com/pypi/simple/
            poetry config virtualenvs.in-project true
        else
            echo -e "${yellow}警告: Poetry安装后可能需要重启终端才能生效${bg}"
        fi
    fi

    # 显示版本信息
    echo -e "${caidan2}Python环境配置完成！${bg}"
    echo -e "${caidan2}Python版本: $($PYTHON_CMD --version)${bg}"
    echo -e "${caidan2}Pip版本: $($PIP_CMD --version)${bg}"
    
    if command -v poetry &>/dev/null; then
        echo -e "${caidan2}Poetry版本: $(poetry --version)${bg}"
    fi

    read -p "按Enter继续..."
}

# 加载插件数据
load_plugins() {
    local category_file="$1"
    local json_file="$MENU_DIR/$category_file"
    
    if [ ! -f "$json_file" ]; then
        echo -e "${red}错误: 找不到配置文件 $json_file${bg}"
        return 1
    fi
    
    jq -r '.[] | "\(.cn_name)|\(.name)|\(.description)|\(.git)"' "$json_file"
}

# 显示插件选择界面
show_plugin_selection() {
    echo -e "${caidan3}┏━━━━━━━━━━ 插件类别 ━━━━━━━━━━┓${bg}"
    echo -e "${caidan1}╭──────────────────────────────╮${bg}"
    local index=1
    for category in "${CATEGORIES[@]}"; do
        IFS=":" read -r name _ <<< "$category"
        echo -e "${caidan2}  $index. $name${bg}"
        ((index++))
    done
    echo -e "${caidan1}╰──────────────────────────────╯${bg}"
    echo -e "${caidan3}┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛${bg}"
}

# 安装普通插件
install_normal_plugin() {
    local name="$1"
    local git_url="$2"
    local cn_name="$3"
    local target_dir="$YZ_DIR/plugins/$name"
    
    # 检查是否为GitHub链接并使用代理
    if [[ "$git_url" == *"github.com"* ]]; then
        local git_url_var="git_url"
        getgh "git_url_var"
        git_url="$git_url_var"
    fi
    
    if [ ! -d "$target_dir" ]; then
        echo -e "${caidan2}正在安装 $cn_name...${bg}"
        if git clone --depth=1 "$git_url" "$target_dir"; then
            echo -e "${green}✓ $cn_name 安装成功!${bg}"
            return 0
        else
            echo -e "${red}✗ $cn_name 安装失败${bg}"
            return 1
        fi
    else
        echo -e "${yellow}! $cn_name 已安装${bg}"
        return 0
    fi
}

# 安装JS插件
install_js_plugin() {
    local cn_name="$1"
    local git_url="$2"
    local target_dir="$YZ_DIR/plugins/example"
    local target_file="$target_dir/${cn_name}.js"

    # 检查是否为GitHub链接并使用代理
    if [[ "$git_url" == *"github.com"* ]]; then
        local git_url_var="git_url"
        getgh "git_url_var"
        git_url="$git_url_var"
    fi
    
    mkdir -p "$target_dir"
    
    if [ ! -f "$target_file" ]; then
        echo -e "${caidan2}正在安装 $cn_name...${bg}"
        if curl -s "$git_url" -o "$target_file"; then
            echo -e "${green}✓ $cn_name 安装成功!${bg}"
            return 0
        else
            echo -e "${red}✗ $cn_name 安装失败${bg}"
            return 1
        fi
    else
        echo -e "${yellow}! $cn_name 已安装${bg}"
        return 0
    fi
}

# Dialog方式显示插件
show_dialog_plugins() {
    local category_name="$1"
    local category_file="$2"
     
    local options=()
    local index=1
    while IFS="|" read -r cn_name name description git; do
        if [ -n "$cn_name" ]; then
            options+=("$index" "$cn_name" "OFF")
            descriptions[$index]="$description"
            ((index++))
        fi
    done < <(load_plugins "$category_file")
    
    dialog --title "向日葵插件安装 - $category_name" \
           --backtitle "向日葵Bot插件管理系统" \
           --checklist "请选择要安装的插件 [空格选择，回车确认]：" 20 70 15 \
           "${options[@]}" 2>/tmp/plugin_selections
           
    if [ $? -eq 0 ]; then
        clear  # 清除dialog残余
        local selections=$(cat /tmp/plugin_selections)
        rm -f /tmp/plugin_selections
        
        for selection in $selections; do
            if [ "$selection" -ge 1 ] && [ "$selection" -le ${#options[@]} ]; then
                local plugin_data=($(load_plugins "$category_file" | sed -n "${selection}p"))
                IFS="|" read -r cn_name name description git <<< "${plugin_data[0]}"
                
                if [ "$category_file" = "js.json" ]; then
                    install_js_plugin "$cn_name" "$git"
                else
                    install_normal_plugin "$name" "$git" "$cn_name"
                fi
            fi
        done
    fi
}

# 文字界面显示插件 (简化版)
show_text_plugins() {
    local category_name="$1"
    local category_file="$2"
    
    while true; do
        clear
        echo -e "${caidan3}┏━━━━━━━━━━ $category_name ━━━━━━━━━━┓${bg}"
        echo -e "${caidan1}╭──────────────────────────────╮${bg}"
        
        local index=1
        local plugins_data=()
        while IFS="|" read -r cn_name name description git; do
            if [ -n "$cn_name" ]; then
                plugins_data+=("$cn_name|$name|$description|$git")
                echo -e "${caidan2}  $index. $cn_name${bg}"
                ((index++))
            fi
        done < <(load_plugins "$category_file")
        
        echo -e "${caidan1}╰──────────────────────────────╯${bg}"
        echo -e "${caidan3}┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛${bg}"
        
        echo -e "${caidan2}输入插件编号安装 (多个用空格分隔)，输入 0 返回${bg}"
        read -p "请选择: " selections
        
        if [ "$selections" = "0" ]; then
            break
        fi
        
        for selection in $selections; do
            if [[ $selection =~ ^[0-9]+$ ]] && [ "$selection" -ge 1 ] && [ "$selection" -le ${#plugins_data[@]} ]; then
                IFS="|" read -r cn_name name description git <<< "${plugins_data[$selection-1]}"
                
                if [ "$category_file" = "js.json" ]; then
                    install_js_plugin "$cn_name" "$git"
                else
                    install_normal_plugin "$name" "$git" "$cn_name"
                fi
            fi
        done
        
        echo -e "${caidan2}是否继续安装此类别的其他插件? (y/n)${bg}"
        read -r continue_install
        if [[ "$continue_install" != "y" ]]; then
            break
        fi
    done
}

# 显示主菜单
show_main_menu() {
    echo -e "${caidan2}输入0或者q退出插件安装脚本${bg}"
    echo -e "${caidan3}┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓${bg}"
    echo -e "${caidan1}╭──────────────────────────────╮${bg}"
    echo -e "${caidan2}         向日葵插件菜单         ${bg}"
    echo -e "${caidan1}───────────────────────────────${bg}"
    echo -e "${caidan2}  1. 安装插件(触屏版)          ${bg}"
    echo -e "${caidan2}  2. 安装插件(文字版)          ${bg}"
    echo -e "${caidan2}  3. 安装李诗雅 js 插件(触屏版) ${bg}"
    echo -e "${caidan2}  4. 安装李诗雅 js 插件(文字版) ${bg}"
    echo -e "${caidan2}  5. 插件文件管理(触屏版)        ${bg}"
    echo -e "${caidan2}  6. 插件文件管理(文字版)        ${bg}"
    echo -e "${caidan2}  7. 配置Python环境            ${bg}"
    echo -e "${caidan2}  8. 切换插件代理(触屏版)        ${bg}"
    echo -e "${caidan2}  9. 切换插件代理(文字版)        ${bg}"
    echo -e "${caidan1}╰──────────────────────────────╯${bg}"
    echo -e "${caidan3}┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛${bg}"
}

# 主程序
main() {
    check_dependencies
    
    while true; do
        clear
        show_main_menu
        read -p "请选择操作: " choice
        
        case "$choice" in
            1|2)
                clear
                show_plugin_selection
                read -p "请选择插件类别 (0-${#CATEGORIES[@]}): " category_choice
                if [ -z "$category_choice" ]; then
                  echo -e "${red}已取消选择${bg}"
                  sleep 2
                elif [ "$category_choice" -ge 1 ] && [ "$category_choice" -le ${#CATEGORIES[@]} ]; then
                  IFS=":" read -r category_name category_file <<< "${CATEGORIES[$category_choice-1]}"
                  if [ "$choice" = "1" ]; then
                    show_dialog_plugins "$category_name" "$category_file"
                    else
                    show_text_plugins "$category_name" "$category_file"
                  fi
                    clear
                    cd "$YZ_DIR" && pnpm i
                  else
                  echo -e "${red}无效的选择${bg}"
                  sleep 2
                fi
                ;;
            3)
                clear
                bash /xrk/body/menu/jsdialog
                clear
                cd "$YZ_DIR" && pnpm i
                ;;
            4)
                clear
                bash /xrk/body/menu/js
                clear
                cd "$YZ_DIR" && pnpm add axios -w && pnpm i
                ;;
            5)
                clear
                bash /xrk/body/menu/deletiondialog
                clear
                cd "$YZ_DIR" && pnpm i
                ;;
            6)
                clear
                bash /xrk/body/menu/deletion
                clear
                cd "$YZ_DIR" && pnpm i
                ;;

            7)
                clear
                install_python_env
                ;;
            8)
                clear
                bash /xrk/body/menu/diaproxy
                clear
                ;;
            9)
                clear
                bash /xrk/body/menu/proxy
                clear
                ;;
            q|0)
                clear
                echo -e "${caidan2}感谢使用，再见！${bg}"
                cd "$YZ_DIR" && pnpm i
                exit 0
                ;;
            *)
                echo -e "${red}无效选择，请重试${bg}"
                sleep 1
                ;;
        esac
    done
}

# 启动主程序
main "$@"